package com.gaokao.demo.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gaokao.demo.constants.Constant;
import com.gaokao.demo.entity.SysUser;
import com.gaokao.demo.service.IUserRoleService;
import com.gaokao.demo.service.IUserService;
import com.gaokao.demo.utils.JwtTokenUtil;
import com.gaokao.demo.vo.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author szs
 * @since 2021-01-22
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    Log log = LogFactory.get();

    public String index() {

        return "";
    }

    /**
     * 登录用户信息
     * @param token
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @ResponseBody
    public String info(@RequestParam("token")String token){
        if (token!=null && token.startsWith(JwtTokenUtil.TOKEN_PREFIX)){

            String s = token.split(JwtTokenUtil.TOKEN_PREFIX)[1];
            ResultResponse resultResponse = new ResultResponse();
            resultResponse.setCode(Constant.SUCCESS_CODE);
            HashMap<String, Object> map = new HashMap<>();
            SysUser sysUser = this.userService.findUserByUserName(JwtTokenUtil.getUsername(s));
            map.put("roles", JwtTokenUtil.getUserRole(s));
            map.put("name", sysUser.getUsername());
            map.put("introduction", "admin");
            map.put("avatar", sysUser.getPhoto());
            resultResponse.setData(map);
            return JSONUtil.toJsonStr(resultResponse);
        }
        return JSONUtil.toJsonStr(ResultResponse.newFail("token error"));
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    @ResponseBody
    public String logout(HttpServletRequest request){
        String header = request.getHeader("X-Token");
        log.info(header);
        if (header==null){
            return JSONUtil.toJsonStr(ResultResponse.newFail("token 为空"));
        }
        if (!header.isEmpty()) {
            ResultResponse resultResponse = new ResultResponse();
            resultResponse.setData("success");
            resultResponse.setCode(Constant.SUCCESS_CODE);
            return JSONUtil.toJsonStr(resultResponse);
        }
        return JSONUtil.toJsonStr(ResultResponse.newFail());
    }

    /**
     * 获取用户列表
     *
     * @param page
     * @param limit
     * @param username
     * @param status
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/getUserList")
    @ResponseBody
    public String getUserList(Integer page, Integer limit, String username, Integer status, String roleId) {
        ResultResponse resultResponse = null;
        IPage<SysUser> userList = userService.getUserList(page, limit, username, status, roleId);
        HashMap<String, Object> map = new HashMap<>();

        if (userList != null && userList.getTotal() > 0) {
            map.put("total", userList.getTotal());
            map.put("items", userList.getRecords());
            resultResponse = ResultResponse.newSuccess("success", map);
        } else {
            map.put("total", 0);
            map.put("items", null);
            resultResponse = ResultResponse.newSuccess("success", map);
        }
        return JSONUtil.toJsonStr(resultResponse);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteUserById")
    @ResponseBody
    public String deleteUserById(String id) {
        ResultResponse resultResponse = null;
        SysUser sysUser = this.userService.getById(id);
        if (sysUser.getUsername().equals("admin")) {
            resultResponse = ResultResponse.newFail("超级管理员无法删除！");
            return JSONUtil.toJsonStr(resultResponse);
        } else {
            if (this.userService.deleteUserById(id)) {
                resultResponse = ResultResponse.newSuccess("删除成功");
                return JSONUtil.toJsonStr(resultResponse);
            } else {
                resultResponse = ResultResponse.newFail("删除失败");
                return JSONUtil.toJsonStr(resultResponse);
            }
        }
    }

    /**
     * 添加用户
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/createUser")
    @ResponseBody
    public String createUser(@RequestBody String map) {
        HashMap sysuer = JSONUtil.toBean(map, HashMap.class);
        String role = sysuer.get("sysRoleList").toString();
        SysUser sysUser = null;
        sysUser = Convert.convert(SysUser.class, sysuer);
        ResultResponse resultResponse = null;
        if (sysUser != null) {
            //密码加密
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            final String passHash = encoder.encode(sysUser.getPassword());
            sysUser.setPassword(passHash);
            this.userService.addUser(sysUser);
            resultResponse = ResultResponse.newSuccess("添加成功");
            HashMap<String, String> data = new HashMap<>();
            data.put("id", sysUser.getId());
            resultResponse.setData(data);
            return JSONUtil.toJsonStr(resultResponse);
        } else {
            resultResponse = ResultResponse.newSuccess("添加失败");
            return JSONUtil.toJsonStr(resultResponse);
        }
    }

    /**
     * 修改用户信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateUser")
    @ResponseBody
    public String updateUser(@RequestBody String map) {
        //密码加密
        HashMap sysuer = JSONUtil.toBean(map, HashMap.class);
        SysUser sysUser = Convert.convert(SysUser.class, sysuer);
        if (sysUser != null && sysUser.getUsername().equals("admin")) {
            return JSONUtil.toJsonStr(ResultResponse.newFail("不能修改超级管理员信息"));
        }
        if (sysUser.getPassword() != null) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            final String passHash = encoder.encode(sysUser.getPassword());
            sysUser.setPassword(passHash);
        }
        this.userService.updateUser(sysUser);
        return JSONUtil.toJsonStr(ResultResponse.newSuccess("更新成功"));
    }




}
